/*
 * @Project_description: http
 */
'use strict'

import axios from "axios"
import {Message} from 'element-ui'
import config from '@/config.js'
import router from '@/router'
import cookie from 'js-cookie'
import qs from "qs";

const service = axios.create({
    timeout: 100000, //超时时间
    baseURL: config.baseUrl,
})

const tokenKey = config.tokenKey

/**
 * @description 请求拦截器
 */
service.interceptors.request.use(
    (config) => {
        let token = cookie.get(tokenKey)
        if (!!token) {
            config.headers['Authorization'] = `Bearer ${token}`
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    (response) => {
        if (response.status === 200) {
            if (response.config.url.indexOf('下载') !== -1) {
                return response
            }
            return response.data
        } else {
            const msg = response.data || '请求失败'
            Message.error(msg)
            return Promise.reject(msg)
        }
    },
    (error) => {
        if (error.status === 401) {
            Message.error('授权失效，请重新登录')
            cookie.remove('用户令牌')
            router.push({path: '/'})
        } else {
            Message.error(error.response.data || '请求失败')
        }
        return Promise.reject(error)
    }
)

/**
 * @description get 请求
 * @return {Promise<any>} 无返回值
 * @param url  {string} 请求地址
 * @param [params] {object} 请求参数
 * @param [headers] {object} 请求头
 */
const get = (url, params = {}, headers = {}) => {
    return new Promise((resolve, reject) => {
        service({
            url,
            method: 'get',
            params,
            headers,
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

/**
 * @description post 请求
 * @return {Promise<any>} 无返回值
 * @param url  {string} 请求地址
 * @param [data] {object} 请求参数
 * @param [headers] {object} 请求头
 */
const post = (url, data = {}, headers = {}) => {
    return new Promise((resolve, reject) => {
        service({
            url,
            method: 'post',
            data,
            headers
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

/**
 * @description put 请求
 * @return {Promise<any>} 无返回值
 * @param url  {string} 请求地址
 * @param [data] {object} 请求参数
 * @param [headers] {object} 请求头
 */
const put = (url, data = {}, headers = {}) => {
    return new Promise((resolve, reject) => {
        service({
            url,
            method: 'put',
            data,
            headers
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

/**
 * @description delete 请求
 * @return {Promise<any>} 无返回值
 * @param url  {string} 请求地址
 * @param [params] {object} 请求参数
 * @param [headers] {object} 请求头
 */
const del = (url, params = {}, headers = {}) => {
    return new Promise((resolve, reject) => {
        service({
            url,
            method: 'delete',
            params,
            headers
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}


const uploadFile = (url, data = {}, headers = {}) => {
    headers['Content-Type'] = 'multipart/form-data'
    data = qs.stringify(data)
    // 创建 FormData 并添加文件
    const formData = new FormData();
    formData.append('excel_file_stream', data);
    return new Promise((resolve, reject) => {
        service({
            url,
            method: 'post',
            data: formData,
            headers
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

const downloadFile = (url, data = {}, headers = {}) => {
    return new Promise((resolve, reject) => {
        service({
            url,
            method: 'post',
            data,
            headers,
            responseType: 'blob'
        }).then(response => {
            try {
                // 获取 Content-Disposition 响应头
                const disposition = response.headers['content-disposition'];
                let fileName = '导出文件.xlsx'; // 默认文件名

                // 解析 Content-Disposition 获取文件名
                if (disposition) {
                    const matches = disposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
                    if (matches && matches[1]) {
                        fileName = decodeURIComponent(matches[1].replace(/['"]/g, ''));
                    }
                }
                // 创建一个临时链接用于下载文件
                const url = window.URL.createObjectURL(new Blob([response.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', fileName); // 设置下载的文件名
                document.body.appendChild(link);
                link.click();

                // 释放临时链接
                window.URL.revokeObjectURL(url);
                return resolve(true)
            } catch (error) {
                console.error('文件下载失败:', error);
                throw error; // 抛出错误以便外部处理
            }
        })
    })
}

export default {
    get,
    post,
    put,
    del,
    uploadFile,
    downloadFile
}
